package cn.yikaojiuguo.student.support.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import java.io.File;

import cn.yikaojiuguo.student.R;
import cn.yikaojiuguo.student.app.YiKaoApplication;
import cn.yikaojiuguo.student.support.simple.ArgsConstants;
import cn.yikaojiuguo.student.ui.base.BaseActivity;

/**
 * Created by cfan_yang on 2016/1/7.
 * 处理拍照或从图库选择照片
 */
public class ImageManager implements View.OnClickListener {

    public final static int PICK_FROM_CAMERA = 1;
    public static final int PICK_FROM_FILE = 2;
    public final static int PICK_FORM_CROP = 3;
    private boolean mNeedCrop = false;
    private int mXRatio, mYRatio;
    private int mCurType = PICK_FROM_CAMERA;
    private Uri mUri = null;
    private OnFinishCompressListener mListener;
    private AlertDialog mDialog;

    private Activity mActivity;

    public ImageManager(Activity activity) {
        this.mActivity = activity;
    }

    public void setOnFinishCompressListener(OnFinishCompressListener listener) {
        this.mListener = listener;
    }

    /**
     * 设置是否需要裁剪
     */
    public ImageManager setNeedCrop(boolean needCrop) {
        this.mNeedCrop = needCrop;
        return this;
    }

    /**
     * 设置裁剪的固定宽高比
     */
    public ImageManager setRatio(int xRatio, int yRatio) {
        mXRatio = xRatio;
        mYRatio = yRatio;
        return this;
    }

    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
        View contentView = View.inflate(mActivity, R.layout.layout_dialog_choose_pic, null);
        contentView.findViewById(R.id.tv_take).setOnClickListener(this);
        contentView.findViewById(R.id.tv_choose).setOnClickListener(this);
        mDialog = builder.create();
        mDialog.show();
        Window window = mDialog.getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setContentView(contentView);
        window.setLayout((int) (Util.getScreenWidthPixels(mActivity) * 0.8), ViewGroup
                .LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_take:
                takePhoto();
                mDialog.dismiss();
                break;
            case R.id.tv_choose:
                choosePhoto();
                mDialog.dismiss();
                break;
        }
    }

    private void choosePhoto() {
        mCurType = PICK_FROM_FILE;
        File choose_file = new File(YiKaoApplication.getCacheImgPath(), ArgsConstants.UPLOAD_IMAGE);
        if (choose_file.exists()) {
            choose_file.delete();
        }
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");// 相片类型
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        mActivity.startActivityForResult(intent, PICK_FROM_FILE);
    }

    /**
     * 拍照获取图片
     */
    private void takePhoto() {
        mCurType = PICK_FROM_CAMERA;
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        File camera_file = new File(YiKaoApplication.getCacheImgPath(), ArgsConstants.UPLOAD_IMAGE);
        if (camera_file.exists()) {
            camera_file.delete();
        }
        LogUtil.showInfoLog("camera", "path = " + camera_file.getAbsolutePath());
        intent.putExtra("output", Uri.fromFile(camera_file));
        mActivity.startActivityForResult(intent, PICK_FROM_CAMERA);
    }

    private void doCrop() {
        if (mCurType == PICK_FROM_CAMERA) {
            File file_in = new File(YiKaoApplication.getCacheImgPath(), ArgsConstants.UPLOAD_IMAGE);
            mUri = Uri.fromFile(file_in);
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(mUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(YiKaoApplication.getCacheImgPath(), ArgsConstants.UPLOAD_IMAGE)));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection

        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);

        if (mXRatio != 0 && mYRatio != 0) {
            intent.putExtra("aspectX", mXRatio);
            intent.putExtra("aspectY", mYRatio);
        }

        mActivity.startActivityForResult(intent, PICK_FORM_CROP);
    }

    /**
     * 在mActivity的onActivityResult调用此方法
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                //拍照
                case PICK_FROM_CAMERA:
                    // 是否需要裁剪
                    if (mNeedCrop) {
                        doCrop();
                    } else {
                        compressImg(YiKaoApplication.getCacheImgPath() + "/" + ArgsConstants
                                .UPLOAD_IMAGE, YiKaoApplication.getCacheImgPath() + "/" +
                                ArgsConstants.UPLOAD_IMAGE);
                    }
                    break;
                //从相册选取
                case PICK_FROM_FILE:
                    mUri = data.getData();
                    if (mNeedCrop) {
                        doCrop();
                    } else {
                        compressImg(UriParser.getImageAbsolutePath(mActivity, mUri),
                                YiKaoApplication.getCacheImgPath() + "/" + ArgsConstants.UPLOAD_IMAGE);
                    }
                    break;
                //裁剪之后
                case PICK_FORM_CROP:
                    if(mCurType == PICK_FROM_CAMERA) {
                        compressImg(YiKaoApplication.getCacheImgPath() + "/" + ArgsConstants
                                .UPLOAD_IMAGE, YiKaoApplication.getCacheImgPath() + "/" + ArgsConstants
                                .UPLOAD_IMAGE);
                    } else if (mCurType == PICK_FROM_FILE) {
                        compressImg(UriParser.getImageAbsolutePath(mActivity, mUri),
                                YiKaoApplication.getCacheImgPath() + "/" + ArgsConstants.UPLOAD_IMAGE);
                    }
                    break;
            }
        }
    }

    private void compressImg(final String fileInPath, final String fileOutPath) {
        if(mActivity instanceof BaseActivity) {
            ((BaseActivity)mActivity).showProgressDialogNotCancel("正在压缩图片...");
        }
        new Thread() {
            @Override
            public void run() {
                Util.compressImg(fileInPath,fileOutPath);
                if(mListener!=null) {
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mListener.onCompressFinish();
                        }
                    });
                }
            }
        }.start();
    }

    public interface OnFinishCompressListener {
        /**
         * 压缩完成
         */
        void onCompressFinish();
    }

}
